package com.gzdh.tang.modu.controller;

import com.alibaba.fastjson.JSONObject;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradePayRequest;
import com.alipay.api.response.AlipayTradePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.vo.Result;

import com.gzdh.tang.config.ali.AliPayUtil;
import com.gzdh.tang.config.weixin.WXEntity;
import com.gzdh.tang.config.weixin.WXPay;
import com.gzdh.tang.config.weixin.WXPayUtils;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.mapper.ReserveMapper;
import com.gzdh.tang.modu.model.*;
import com.gzdh.tang.modu.model.dk.JsonsRootBean;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.modu.util.ALiUtils;
import com.gzdh.tang.modu.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.lang.Thread.sleep;

@Slf4j
@RestController
@RequestMapping("api/AliFace")
public class ALiFacePayController {


    @Autowired
    ReserveService reserveService;

    @Autowired
    FkService fkService;

    @Autowired
    MacMainpSbruanService macMainpSbruanService;

    @Autowired
    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    @Autowired
    MacMainpSbruanKlService macMainpSbruanKlService;

    @Autowired
    ReserveMapper reserveMapper;

    @Autowired
    AliFaceOrdersService aliFaceOrdersService;

//    @Autowired
//    MacMainpSbruanKlDinnerService macMainpSbruanKlPriceService;

    @Autowired
    MacMainpSbruanKlButieService macMainpSbruanKlButieService;

    @Autowired
    MacMainpSbruanKlDinnerService macMainpSbruanKlDinnerService;

    @Autowired
    WxFaceOrdersService wxFaceOrdersService;


    @Autowired
    GsService gsService;

    /**
     * 在线刷卡消费
     *
     * @param deviceId
     * @param price
     * @param cardsn
     * @param tradeNo
     * @param sessionId
     * @return
     */
    @PostMapping("cardPay")
    public Result<Object> cardPay(@RequestParam("deviceId") String deviceId, @RequestParam("price") String price,
                                  @RequestParam("cardsn") String cardsn, @RequestParam("tradeNo") String tradeNo, @RequestParam("sessionId") String sessionId) {
        Result<Object> result = new Result<>();
        AliPayResVo aliPayResultVo = new AliPayResVo();
        try {
            Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
            reserveService.toCardPay(deviceId, new BigDecimal(price).multiply(new BigDecimal(100)).intValue(), fk, tradeNo, new LinkedList<>());
            fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
            aliPayResultVo.setFk(fk);
        } catch (Exception e) {
            e.printStackTrace();
            aliPayResultVo.setSuccess(false);
            aliPayResultVo.setMsg(e.getMessage());
            aliPayResultVo.setUserName("支付失败");
            aliPayResultVo.setTradeNo(tradeNo);
            aliPayResultVo.setSessionId(sessionId);
            aliPayResultVo.setAmount(price);
            result.setResult(JSONObject.toJSON(aliPayResultVo));
            return result;
        }
        aliPayResultVo.setSuccess(true);
        aliPayResultVo.setMsg("支付成功");
        aliPayResultVo.setUserName("测试");
        aliPayResultVo.setTradeNo(tradeNo);
        aliPayResultVo.setSessionId(sessionId);
        aliPayResultVo.setAmount(price);
        result.setResult(JSONObject.toJSON(aliPayResultVo));
        return result;
    }


    /**
     * 在线刷脸，不够则走代扣，
     * 如果金额不够时，将记录插入到临时表中，通过调度中心进行查单进行代扣，走代扣接口时不用等待支付宝的结果
     *
     * @param tradeNo
     * @param sessionId
     * @param deviceId
     * @return
     */
    @PostMapping("facePay")
    public Result<Object> facePay(@RequestParam("tradeNo") String tradeNo, @RequestParam("sessionId") String sessionId, @RequestParam("deviceId") String deviceId, @RequestParam("price") String price, @RequestParam("faceToken") String faceToken, @RequestParam("aliUid") String aliUid, @RequestParam("terminal_params") String terminal_params) {
        Result<Object> result = new Result<>();
        String orders = "ALI" + tradeNo;
        String senceNo = "";
        String dinner = "";
        int tokenType = 0;
        if (faceToken.length() > 18) {
            tokenType = 2;
        } else if ("1".equals(faceToken.substring(0, 1))) {
            tokenType = 1;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            orders = "WXZF" + sdf.format(new Date());
        } else if ("2".equals(faceToken.substring(0, 1))) {
            tokenType = 2;
            if (StringUtils.isEmpty(aliUid)) {
                //通过付款码，去获取uid
                Map<String, String> res = ALiUtils.getAliUid(faceToken);
                aliUid = res.get("aliUid");
                senceNo = res.get("sence_no");
            }
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        AliFaceOrders aliFaceOrders = new AliFaceOrders();
        AliPayResVo aliPayResultVo = new AliPayResVo(tradeNo, sessionId, price);
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getAliUserId, aliUid));
        if (fk == null) {
            if (macMainpSbruan.isAnonymity() && !StringUtils.isEmpty(macMainpSbruan.getAliCardno()) && tokenType == 2) {
                fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, macMainpSbruan.getAliCardno()));
                if (fk == null) {
                    aliPayResultVo.setSuccess(false);
                    aliPayResultVo.setMsg("查无此人");
                    aliPayResultVo.setUserName("FK表没记录");
                    result.setResult(JSONObject.toJSON(aliPayResultVo));
                    return result;
                }
                boolean temp = havePost(orders, price, faceToken, terminal_params, senceNo);
                if (temp) {
                    insertReserve("4", deviceId, orders, fk.getCardsn(), new BigDecimal(price), "0", fk, macMainpSbruan);
                    aliPayResultVo.setFk(fk);
                    aliPayResultVo.setSuccess(true);
                    aliPayResultVo.setMsg("支付成功");
                    result.setResult(JSONObject.toJSON(aliPayResultVo));
                    return result;
                }
            } else if (tokenType == 1) {


                fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, macMainpSbruan.getCardno()));
                if (fk == null) {
                    aliPayResultVo.setSuccess(false);
                    aliPayResultVo.setMsg("查无此人");
                    aliPayResultVo.setUserName("FK表没记录");
                    result.setResult(JSONObject.toJSON(aliPayResultVo));
                    return result;
                }
                //微信付款码
                WxFaceOrders wxFaceOrders = new WxFaceOrders();
                wxFaceOrders.setOrders(orders);
                wxFaceOrders.setPrice(price);
                wxFaceOrders.setDeviceId(deviceId);
                wxFaceOrders.setDinner(dinner);
                wxFaceOrders.setCreateTime(new Date());
                wxFaceOrders.setCardno(fk.getCardno());
                wxFaceOrders.setTradeNo(tradeNo);
                wxFaceOrdersService.save(wxFaceOrders);
                weixinPay(faceToken, orders, price);
                aliPayResultVo.setSuccess(true);
                aliPayResultVo.setMsg(orders);
                result.setResult(JSONObject.toJSON(aliPayResultVo));
                return result;
            }
            aliPayResultVo.setSuccess(false);
            aliPayResultVo.setMsg("查无此人");
            aliPayResultVo.setUserName("FK表没记录");
            result.setResult(JSONObject.toJSON(aliPayResultVo));
            return result;
        }

        aliPayResultVo.setFk(fk);
        if (new BigDecimal(fk.getKye()).add(new BigDecimal(fk.getBtye())).compareTo(new BigDecimal(price)) == 1) {
            try {
                toSaveReserve2(fk, deviceId, tradeNo, price, orders);
                aliFaceOrders.setState(true);
            } catch (RuntimeException e) {
                aliFaceOrders.setState(false);
                e.printStackTrace();
                aliPayResultVo.setSuccess(false);
                aliPayResultVo.setMsg(e.getMessage());
                aliPayResultVo.setUserName("支付失败");
                result.setResult(JSONObject.toJSON(aliPayResultVo));
                return result;
            }
        } else if (StringUtils.isEmpty(fk.getAliAgreementNo())) {
            aliPayResultVo.setSuccess(false);
            aliPayResultVo.setMsg("余额不足");
            aliPayResultVo.setUserName("支付失败");
            result.setResult(JSONObject.toJSON(aliPayResultVo));
            return result;
        }
        aliFaceOrders.setAliUid(aliUid);
        aliFaceOrders.setAuthCode(faceToken);
        aliFaceOrders.setDeviceId(deviceId);
        aliFaceOrders.setSessionId(sessionId);
        aliFaceOrders.setTradeNo(tradeNo);
        aliFaceOrders.setPrice(price);
        aliFaceOrders.setCardno(fk.getCardno());
        aliFaceOrders.setAliAgreementNo(fk.getAliAgreementNo());
        aliFaceOrders.setOrders(orders);
        aliFaceOrders.setDinner(dinner);
        aliFaceOrders.setTerminalParams(terminal_params);
        aliFaceOrdersService.save(aliFaceOrders);

        aliPayResultVo.setSuccess(true);
        aliPayResultVo.setMsg("支付成功");
        aliPayResultVo.setUserName("测试");

        result.setResult(JSONObject.toJSON(aliPayResultVo));
        return result;
    }

    private boolean havePost(String orders, String orderPrice, String authCode, String terminalParams, String senceNo) {
        try {
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AliPayUtil.getAppid(), AliPayUtil.getPrivateKey(), "json", "GBK", AliPayUtil.getPublicKey(), "RSA2");
            AlipayTradePayRequest request = new AlipayTradePayRequest();
            JsonsRootBean jsonsRootBean;
            jsonsRootBean = new JsonsRootBean(orders, orderPrice, authCode, terminalParams, senceNo);
            request.setBizContent(JSONObject.toJSONString(jsonsRootBean));
            AlipayTradePayResponse response = alipayClient.execute(request, null, AliPayUtil.getAppAuthToken());
            if (response.isSuccess()) {
                System.out.println("调用成功");
                return true;
            } else {
                System.out.println("调用失败");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    private Boolean toSaveReserve2(Fk fk, String deviceId, String tradeNo, String price, String orders) throws RuntimeException {
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
        try {
            String dinner = getDinner(macMainpSbruan).trim();
            macMainpSbruan.setDinner(dinner);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("餐次获取失败");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda().eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        BigDecimal shengyuPrice = new BigDecimal(price);
        while ((new BigDecimal(fk.getKye()).compareTo(new BigDecimal(0)) == 1 || new BigDecimal(fk.getBtye()).compareTo(new BigDecimal(0)) == 1) && shengyuPrice.compareTo(new BigDecimal(0)) == 1) {
            //循环条件： 卡余额和补贴余额不为0，并且还存在未消费金额
            //则需要重新循环判断扣除调金额
            BigDecimal priceTemp = insertReserve(deviceId, tradeNo, shengyuPrice, "0", fk, macMainpSbruan, orders, 0);
            shengyuPrice = shengyuPrice.subtract(priceTemp);
        }
        //判断是否开通代扣，如果没有开通代扣则返回失败操作
        if (shengyuPrice.compareTo(new BigDecimal(0)) == 1) {
            throw new RuntimeException("余额不足");
        }
        return true;
    }


    private BigDecimal insertReserve(String rgTermSN, String reqSeqNo, BigDecimal xfPrice, String dateStr, Fk fk, MacMainpSbruan macMainpSbruan, String orders, int type) throws RuntimeException {
        BigDecimal yePrice = new BigDecimal(0);
        String sc = "0";
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        Date date = new Date();
        if ("0".equals(dateStr)) {
            date = new Date();
            if (btye.compareTo(new BigDecimal(0)) == 1) {
                sc = "1";
                yePrice = btye.subtract(xfPrice);
                if (btye.compareTo(xfPrice) < 0) {
                    //补贴小于消费，直接写补贴
                    xfPrice = btye;
                    btye = new BigDecimal(0);
                } else {
                    btye = btye.subtract(xfPrice);
                }
            } else if (kye.compareTo(new BigDecimal(0)) == 1) {
                sc = "0";
                yePrice = kye.subtract(xfPrice);
                if (kye.compareTo(xfPrice) < 0) {
                    xfPrice = kye;
                    kye = new BigDecimal(0);
                } else {
                    kye = kye.subtract(xfPrice);
                }
            } else if (type == 4) {
                sc = "4";
                yePrice = new BigDecimal(0);
            }
        } else {
            try {
                date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr);
            } catch (Exception e) {
                throw new RuntimeException("时间异常");
            }
        }
        btye = btye.setScale(2, BigDecimal.ROUND_HALF_UP);
        kye = kye.setScale(2, BigDecimal.ROUND_HALF_UP);
        xfPrice = xfPrice.setScale(2, BigDecimal.ROUND_HALF_UP);
        Reserve reserve = new Reserve();
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(macMainpSbruan.getBqh());
        reserve.setKsh(macMainpSbruan.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(macMainpSbruan.getCode());
        reserve.setSl(1);
        reserve.setJe(xfPrice.toPlainString());
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {
            log.error("余额错误");
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname("现金菜");
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(orders);
        reserve.setAddr(macMainpSbruan.getAddr());
        reserveService.save(reserve);
        fk.kye = kye.toPlainString();
        fk.btye = btye.toPlainString();
        return xfPrice;
    }

    private String getDinner(MacMainpSbruan macMainpSbruan) throws Exception {
        String hourMin = new SimpleDateFormat("HH:mm").format(new Date());
        List<MacMainpSbruanDinner> macMainpSbruanDinnerList = macMainpSbruanDinnerService.list(new QueryWrapper<MacMainpSbruanDinner>().lambda().eq(MacMainpSbruanDinner::getDeviceId, macMainpSbruan.getId()));
        for (MacMainpSbruanDinner goo : macMainpSbruanDinnerList) {
            if (DateUtil.hourMinuteBetween(hourMin, goo.getStartTime(), goo.getEndTime())) {
                return goo.getDinner();
            }
        }
        throw new Exception("未找到该灶类");
    }


    private boolean judeKl(List<MacMainpSbruanKl> macMainpSbruanKlList, String kl) {
        for (MacMainpSbruanKl goo : macMainpSbruanKlList) {
            if (goo.getKl().equals(kl.trim())) {
                return true;
            }
        }
        return false;
    }


    @GetMapping("tongji")
    public Result<Object> getTongji(@RequestParam("deviceId") String deviceId) {
        Result<Object> result = new Result<>();
        String czrq = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<ReserveTongji> reserveTongjiList = reserveMapper.getReserve(deviceId, czrq);
        result.setResult(reserveTongjiList);
        return result;
    }


    @GetMapping("getOrder")
    public Result<Object> getOrder(@RequestParam("deviceId") String deviceId) {
        Result<Object> result = new Result<>();
        String czrq = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<OrderModel> orderModelList = reserveMapper.getOrderModel(deviceId, czrq);
        for (int i = 0; i < orderModelList.size(); i++) {
            orderModelList.get(i).setIndex(i);
            orderModelList.get(i).setSelected(i == 0);
        }
        result.setResult(orderModelList);
        return result;
    }

    @GetMapping("DeviceSign")
    public Result<Object> deviceSign(@RequestParam("deviceId") String deviceId) {
        Result<Object> result = new Result<>();
        String poeNum = macMainpSbruanService.getDeviceSign(deviceId);
        result.setResult(poeNum);
        return result;
    }

    @PostMapping("upLoadOrder")
    public Result<Object> upLoadOrder(@RequestParam("amount") String amount, @RequestParam("authCode") String authCode, @RequestParam("cardno") String cardno, @RequestParam("tradeNo") String tradeNo, @RequestParam("deviceId") String deviceId, @RequestParam("createTime") long createTimeLong) {
        Result<Object> result = new Result<>();
        Date createTime = new Date(createTimeLong);
        System.out.println("机号" + deviceId);
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardno, cardno));
        String dinner = macMainpSbruanService.getDinnerByDeviceId(deviceId, createTime);

        AliFaceOrders aliFaceOrders = new AliFaceOrders();
        aliFaceOrders.setAliUid("");
        aliFaceOrders.setAuthCode(authCode);
        aliFaceOrders.setDeviceId(deviceId);
        aliFaceOrders.setSessionId("");
        aliFaceOrders.setTradeNo(tradeNo);
        aliFaceOrders.setPrice(amount);
        aliFaceOrders.setCardno(cardno);
        aliFaceOrders.setAliAgreementNo("");
        aliFaceOrders.setOrders("Ali" + tradeNo);
        aliFaceOrders.setDinner(dinner);
        if (fk != null) {
            aliFaceOrders.setAliAgreementNo(fk.getAliAgreementNo());
            aliFaceOrders.setAliUid(fk.getAliUserId());
        }
        aliFaceOrdersService.save(aliFaceOrders);
        org.apache.commons.lang.StringUtils.isBlank("");
        return result;
    }


    /**
     * 消费卡类对照表
     * <p>
     * 通过刷卡实现方法
     *
     * @param cardsn
     * @return
     */
//    private Result<Object> cardPay(String cardsn) {
//        Result<Object> result = new Result<>();
//        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
//        if (fk == null) {
//            return Result.error("非法卡");
//        }
//        MacMainpSbruanKlDinner macMainpSbruanKlPrice = macMainpSbruanKlPriceService
//                .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda().eq(MacMainpSbruanKlDinner::getKl, fk.getKl()));
//        if (macMainpSbruanKlPrice == null) {
//            return Result.error("不支持此卡类");
//        }
//        return result;
//    }

    /**
     * 通过二维码发起支付
     *
     * @return
     */
    @PostMapping("toQrPay")
    public Result<Object> toQrPay(@RequestParam("authCode") String qr, @RequestParam("deviceId") String deviceIds, @RequestParam("price") String price, @RequestParam("order") String orders) {

        Result<Object> result = new Result<>();
        if ("1".equals(qr.substring(0, 1))) {
            //微信支付
            QrPayModel qrPayModel = weixinPay(qr, orders, price);
            result.setResult(qrPayModel);
        } else if ("2".equals(qr.substring(0, 1))) {
            //支付宝支付

        }
        return result;
    }


    @PostMapping("checkQrOrders")
    public Result<Object> checkQrOrders(@RequestParam("order") String order) {
        Result<Object> result = new Result<>();
        QrPayModel qrPayModel = weixinQrCheck(order);
        result.setResult(qrPayModel);
        return result;
    }

    private QrPayModel weixinPay(String qrCode, String order, String price) {
        WXEntity wxEntity = new WXEntity();
        price = new BigDecimal(price).multiply(new BigDecimal(100)).stripTrailingZeros().toPlainString();
        Map<String, String> res = null;
        QrPayModel qrPayModel = new QrPayModel();
        qrPayModel.setSuccess(false);
        qrPayModel.setMsg("支付失败");
        qrPayModel.setCode(-1);
        try {
            //region 向微信发起支付
            WXPay wxPay = new WXPay(wxEntity);
            Map<String, String> reqData = new HashMap<>();
            if (WXPayUtils.getSubmchMode() == 1) {
                //子商户模式
                reqData.put("sub_mch_id", WXPayUtils.getSubMchId());
            }
            reqData.put("body", "消费机");  //商品
            reqData.put("auth_code", qrCode);  //付款码
            reqData.put("spbill_create_ip", "8.8.8.8");//终端ip
            reqData.put("out_trade_no", order);
            reqData.put("total_fee", String.valueOf(price));
            res = wxPay.microPay(reqData, 10 * 1000, 10 * 1000);
            //endregion
            if ("SUCCESS".equals(res.get("return_code")) && "SUCCESS".equals(res.get("result_code"))) {
                log.info("交易成功");
                qrPayModel.setSuccess(true);
                qrPayModel.setMsg("支付成功");
                qrPayModel.setCode(1);
                return qrPayModel;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrPayModel;
    }


    private QrPayModel weixinQrCheck(String order) {
        WXEntity wxEntity = new WXEntity();
        Map<String, String> res = null;
        QrPayModel qrPayModel = new QrPayModel();
        qrPayModel.setSuccess(false);
        qrPayModel.setMsg("支付失败");
        qrPayModel.setCode(-1);
        try {
            WXPay wxPay = new WXPay(wxEntity);
            Map<String, String> reqData = new HashMap<>();
            reqData = new HashMap<>();
            if (WXPayUtils.getSubmchMode() == 1) {
                //子商户模式，添加子商户号
                reqData.put("sub_mch_id", WXPayUtils.getSubMchId());
            }
            reqData.put("out_trade_no", order);
            res = wxPay.orderQuery(reqData, 10 * 1000, 10 * 1000);

            if ("SUCCESS".equals(res.get("result_code")) && "SUCCESS".equals(res.get("return_code"))) {
                //成功返回
                String trade_state = res.get("trade_state");
                if ("SUCCESS".equals(trade_state)) {
                    qrPayModel.setSuccess(true);
                    qrPayModel.setMsg("支付成功");
                    qrPayModel.setCode(1);
                    return qrPayModel;
                } else if ("USERPAYING".equals(trade_state) || "ACCEPT".equals(trade_state)) {
                    //正在支付中
                    qrPayModel.setSuccess(false);
                    qrPayModel.setMsg("请输入密码");
                    qrPayModel.setCode(0);
                    return qrPayModel;
                } else {
                    log.info("交易失败,请撤单");
                    qrPayModel.setSuccess(false);
                    qrPayModel.setMsg("支付失败");
                    qrPayModel.setCode(-1);
                    return qrPayModel;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return qrPayModel;
    }

    /**
     * 核销模式下，先获取当前机器的餐次，再判断fk表，从fk表中获取卡类判断卡获取消费金额，向reserve写数据
     *
     * @return
     */
    @PostMapping("hexiao1")
    public Result<Object> hexiao(@RequestParam("deviceId") String deviceId,
                                 @RequestParam(name = "authCode", required = false) String authCode,
                                 @RequestParam(name = "faceToken", required = false) String faceToken,
                                 @RequestParam(name = "aliUid", required = false) String aliUid,
                                 @RequestParam("sessionId") String sessionId,
                                 @RequestParam("tradeNo") String tradeNo, @RequestParam("terminal_params") String terminal_params) {
        Result<Object> result = new Result<>();
        try {
            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
            if (macMainpSbruan == null) {
                return Result.error("设备未找到或者设备有误，请核对操作");
            }
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            JSONObject req = new JSONObject();
            req.put("authCode", authCode);
            req.put("deviceId", deviceId);
            req.put("faceToken", faceToken);
            req.put("aliUid", aliUid);
            req.put("sessionId", sessionId);
            req.put("tradeNo", tradeNo);
            req.put("terminal_params", terminal_params);
            if (StringUtils.isEmpty(aliUid)) {
                JSONObject resJson = ruleHandler.toQrPay(req);
                result.setResult(resJson);
            } else {
                JSONObject resJson = ruleHandler.toFacePay(req);
                result.setResult(resJson);
            }
        } catch (Exception e) {
            e.printStackTrace();
            HexiaoOrderModel hexiaoOrderModel = new HexiaoOrderModel();
            hexiaoOrderModel.setMsg("系统错误");
            result.setResult(hexiaoOrderModel);
        }
        return result;
    }

    @Autowired
    MacMainpSbruanPayruleService macMainpSbruanPayruleService;

    /**
     * @return
     */
    @PostMapping("cardHexiao")
    public Result<Object> cardHexiao(@RequestParam("deviceId") String deviceId, @RequestParam(name = "cardSn") String cardsn) {
        Result<Object> result = new Result<>();
        try {
            MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda().eq(MacMainpSbruan::getMac, deviceId));
            if (macMainpSbruan == null) {
                return Result.error("设备未找到或者设备有误，请核对操作");
            }
            MacMainpSbruanPayrule macMainpSbruanPayrule = macMainpSbruanPayruleService.getById(macMainpSbruan.getPayRule());
            IPayRuleHandler ruleHandler = (IPayRuleHandler) Class.forName(macMainpSbruanPayrule.getClassName()).newInstance();
            JSONObject req = new JSONObject();
            req.put("cardsn", cardsn);
            req.put("deviceId", deviceId);
            JSONObject resJson = ruleHandler.toCardPay(req);
            result.setResult(resJson);
        } catch (Exception e) {
            e.printStackTrace();
            HexiaoOrderModel hexiaoOrderModel = new HexiaoOrderModel();
            hexiaoOrderModel.setMsg("系统错误");
            result.setResult(hexiaoOrderModel);
        }
        return result;

    }


    private boolean insertReserve(String sc, String rgTermSN, String reqSeqNo, String cardsn, BigDecimal price, String dateStr, Fk fk, MacMainpSbruan macMainpSbruan) throws RuntimeException {
        BigDecimal xfPrice = price;
        BigDecimal yePrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        Date date = new Date();
        if ("0".equals(dateStr)) {
            date = new Date();
        } else {
            try {
                date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr);
            } catch (Exception e) {
                throw new RuntimeException("时间异常");
            }
        }
        Reserve reserve = new Reserve();
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(fk.getBqh());
        reserve.setKsh(fk.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(macMainpSbruan.getCode());
        reserve.setSl(1);
        reserve.setJe(price.toPlainString());
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {
            log.error("余额错误");
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname("现金菜");
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setOpenid(cardsn);
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(String.valueOf(reqSeqNo));
        reserve.setAddr(macMainpSbruan.getAddr());
        reserveService.save(reserve);
        return true;
    }


}
